import React from 'react';
import _ from 'lodash';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import classNames from 'classnames';
import {
  API_URL,
  formItemLayout,
  _validate,
  check_rules,
  available,
  checkExists,
  fetchDatum,
  portraitSet,
  fetchAttachByEntry,
  fetchAttachById,
  special_operate,
  getUser,
  putPW
} from '../../store/actions';
import {message, Radio, Checkbox, Button, Select, Input, Form, Icon, Switch, Table, Upload, Alert,Tag,Row,Col,Tabs} from 'antd';

function noop() {
    return false;
}
const TabPane = Tabs.TabPane,
  CheckboxGroup = Checkbox.Group,
  FormItem = Form.Item,
  Option = Select.Option,
  RadioGroup = Radio.Group,
  RadioButton = Radio.Button,
  tempServiceData = [
    {
        id: 'time0',
        label: '9:00-12:00'
    }, {
        id: 'time1',
        label: '14:00-17:00'
    }, {
        id: 'time2',
        label: '19:00-21:00'
    }
];
class BaseInfo extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            data: null,
            portrait: this.props.portrait,
            fileList:{},
            user: this.props.user
        }
    }
    setFieldsValue(){
        const user = this.state.user.user,
          initData = {
              name:user.name,
              gender:user.gender,
              idcard:user.idcard,
              brief_introduction:user.brief_introduction
          },
          initForm = this.props.form.setFieldsValue;
        initForm(initData)
    }
    componentWillMount(){
        this.setFieldsValue()
    }
    componentWillReceiveProps(nextProp){
        this.setState({
            data:nextProp.data,
            portrait:nextProp.portrait,
            user:nextProp.user
        })
    }
    normFile(e) {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }
    portraitHandler(info){
        const _this = this;
        return portraitSet(info,_this)
    }
    fileTypeLimit(types,file){
        const fileType = file.type,
          typeStr = types.join('、');
        let isOk = false;
        for(let i = 0;i<types.length;i++){
            try{
                isOk = new RegExp(types[i]).test(fileType);
                if(isOk){
                    break;
                }
            }catch(e){consloe.log(e)}
        }
        if(!isOk){
            message.error(`您上传文件的格式只能是：${typeStr}格式`);
            return isOk
        }
    }
    checkName(rule, value, callback) {
        this.props.checkForm('account', 'name', rule, value, callback)
    }
    checkIdcard(rule, value, callback) {
        this.props.checkForm('common', 'idcard', rule, value, callback)
    }
    handleSubmit(e){
        e.preventDefault();
        const _this = this;
        _validate(e, _this, function (data) {
            let _data = Object.assign({}, data);
            let attachment = [],
              willUploadFiles = _this.state.fileList;
            _.forIn(willUploadFiles,(v,k)=>{
                if(v.length> 0 ){
                    attachment.push({[k]:v})
                }
            });
            _data.attachment = attachment;
            _data.specialist_id = _this.state.user.user.specialist_id;
            _data.account_id = _this.state.user.user.account_id;
            _this.props.dispatch(special_operate('update',{}, _data, function () {
                message.success('信息更新成功', 3);
                _this.props.updateUser(_data)
            }))
        })
    }
    render(){
        if(!this.state.data){
            return (<div>加载中</div>)
        }
        const _gender = this.state.data.gender && this.state.data.gender.map(_g => {
                return (<RadioButton key={_g.id} value={_g.code}>{_g.name}</RadioButton>)
            }),
          {getFieldProps} = this.props.form;

        const specialistName = getFieldProps('name', {
            rules: [
                {required: true, message: '请输入医生姓名'},
                {validator: this.checkName.bind(this)}
            ]
        });
        const idCardProps = getFieldProps('idcard', {
            rules: [
                {required: false},
                {validator: this.checkIdcard.bind(this)}
            ]
        });
        const genderProps = getFieldProps('gender', {
            rules: [
                {required: true, message: '请选择专家性别'}
            ]
        });
        const specialistDesc = getFieldProps('brief_introduction', {
            rules: [
                {required: true, message: '请输入医生介绍'},
                {max: 5000, message: '超过了最大长度5000'}
            ]
        });
        const portraitProps = getFieldProps('portrait', {
            normalize: this.normFile.bind(this),
            onChange: this.portraitHandler.bind(this)
        });
        let curPortrait = null;
        if(this.state.fileList && this.state.fileList.portrait){
            curPortrait = {};
            const _id = this.state.fileList.portrait;
            curPortrait.id = _id;
            curPortrait.url = `${API_URL}attachment/${_id}?accessToken=${this.state.user.accessToken}`
        }else{
            curPortrait = this.state.portrait
        }
        return (
          <Form horizontal form={this.props.form}>
              <FormItem
                {...formItemLayout}
                label="专家头像"
              >
                  <Upload
                    name="files"
                    showUploadList={false}
                    action={`${API_URL}upload/portrait?accessToken=${this.props.user.accessToken}`}
                    beforeUpload = {this.fileTypeLimit.bind(this,['jpg','gif','png','jpeg'])}
                    help="只能上传图片格式的文件"
                    {...portraitProps}
                  >
                      <div style={{
                                width: '100px',
                                overflow: 'hidden',
                                backgroundColor: '#ddd',
                                textAlign: 'center'
                            }}>
                          {curPortrait?<img style={{
                            display: 'block',
                            width: '100%'
                        }} src={curPortrait.url} />:'没有上传头像'}
                      </div>
                      <Button type="ghost">
                          <Icon type="upload" /> 选择并上传头像
                      </Button>
                  </Upload>
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="姓名"
              >
                  <Input
                    {...specialistName}
                    placeholder="请输入真实姓名"
                  />
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="性别"
              >
                  <RadioGroup {...genderProps}>
                      {_gender}
                  </RadioGroup>
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="身份证号"
              >
                  <Input {...idCardProps} placeholder="请输入身份证号"/>
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="简介"
              >
                  <Input type="textarea" {...specialistDesc} />
              </FormItem>
              <FormItem wrapperCol={formItemLayout.noLabel}>
                  <Button type="primary" onClick={this.handleSubmit.bind(this)}>保存</Button>
                  &nbsp;&nbsp;&nbsp;&nbsp;
                  <Button onClick={this.setFieldsValue.bind(this)}>重置</Button>
              </FormItem>
          </Form>
        )
    }
}
BaseInfo = Form.create()(BaseInfo);
class ProInfo extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            data: this.props.data,
            user: this.props.user
        }
    }
    setFieldsValue(){
        const user = this.state.user.user,
          initData = {
              hospital:user.hospital,
              modalities:user.modalities,
              department:user.department,
              title:user.title,
              domain:user.domain
          },
          initForm = this.props.form.setFieldsValue;
        initForm(initData)
    }
    componentWillMount(){
        this.setFieldsValue()
    }
    componentWillReceiveProps(nextProp){
        this.setState({
            data:nextProp.data,
            user:nextProp.user
        })
    }
    handleSubmit(e){
        e.preventDefault();
        const _this = this;
        _validate(e, _this, function (data) {
            let _data = Object.assign({}, data);
            _data.account_id = _this.state.user.user.account_id;
            _this.props.dispatch(special_operate('update',{}, _data, function () {
                message.success('信息更新成功', 3);
                _this.props.updateUser(_data)
            }))
        })
    }
    render(){
        if(!this.state.data){
            return (<div>加载中</div>)
        }
        const _modalities = this.state.data.modality && _.map(this.state.data.modality, (_m) => {
                return {
                    label: _m.code,
                    value: _m.id
                }
            }),
          _departments = this.state.data.department && this.state.data.department.map(_h => {
                return (<Option key={_h.id} value={_h.name}>{_h.name}</Option>)
            }),

          _title = this.state.data.title && this.state.data.title.map(_h => {
                return (<Option key={_h.id} value={_h.name}>{_h.name}</Option>)
            }),
          {getFieldProps} = this.props.form;

        const specialistHospital = getFieldProps('hospital', {
            rules: [
                {required: true, message: '请选择所属医院'},
                {max: 100, message: '所属医院最大长度为100'}
            ]
        }),
          specialistDepartment = getFieldProps('department', {
            rules: [
                {required: true, message: '请选择所属科室'}
            ]
        }),
          specialistTitle = getFieldProps('title', {
            rules: [
                {required: true, message: '请选择职称'}
            ]
        }),
          specialistDomain = getFieldProps('domain', {
            rules: [
                {required: true, message: '请输入医生擅长领域'},
                {max: 5000, message: '超过了最大长度5000'}
            ]
        }),
          specialistModalities = getFieldProps('modalities', {
            rules: [
                {required: true, type: 'array', message: '请勾选医生阅片类型'}
            ]
        });
        return (
          <Form horizontal form={this.props.form}>
              <FormItem
                {...formItemLayout}
                label="职称"
              >
                  <Select
                    {...specialistTitle}
                    showSearch
                    placeholder="请选择职称"
                    optionFilterProp="children"
                    notFoundContent="无法找到"
                  >
                      {_title}
                  </Select>
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="所属医院"
              >
                  <Input {...specialistHospital} placeholder="请输入所属医院"/>
              </FormItem>
              <FormItem {...formItemLayout} label="所属科室">
                  <Select
                    {...specialistDepartment}
                    showSearch
                    placeholder="请选择所属科室"
                    optionFilterProp="children"
                    notFoundContent="无法找到"
                  >
                      {_departments}
                  </Select>
              </FormItem>
              <FormItem {...formItemLayout.ignore} label="阅片类型">
                  <CheckboxGroup
                    {...specialistModalities}
                    options={_modalities}
                  />
              </FormItem>
              <FormItem {...formItemLayout} label="擅长领域">
                  <Input type="textarea" {...specialistDomain} />
              </FormItem>
              <FormItem wrapperCol={formItemLayout.noLabel}>
                  <Button type="primary" onClick={this.handleSubmit.bind(this)}>保存</Button>
                  &nbsp;&nbsp;&nbsp;&nbsp;
                  <Button
                    onClick={this.setFieldsValue.bind(this)}
                  >
                      重置
                  </Button>
              </FormItem>
          </Form>
        )
    }
}
ProInfo = Form.create()(ProInfo);
class ServerInfo extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            user: this.props.user
        }
    }
    setFieldsValue(){
        const user = this.state.user.user,
          initData = {
              workingtime:user.workingtime
          },
          initForm = this.props.form.setFieldsValue;
        if (initData.workingtime == '[]') {
        } else {
            //有数据
            const _wt = initData.workingtime;
            if(_wt) {
                _wt.forEach(_w => {
                    initData[_w.label] = _w.weekday
                });
            }
            delete initData.workingtime
        }
        initForm(initData)
    }
    componentWillMount(){
        this.setFieldsValue()
    }
    componentWillReceiveProps(nextProp){
        this.setState({
            user:nextProp.user
        })
    }
    handleSubmit(e){
        e.preventDefault();
        const _this = this;
        _validate(e, _this, function (data) {
            let _data = Object.assign({}, data);
            let workingtime = [];
            for (let _e in data) {
                const _reg = /^time\d+/;
                if (_reg.test(_e)) {
                    const _wt = {
                        label: _e,
                        weekday: data[_e]
                    };
                    workingtime.push(_wt);
                    delete _data[_e];
                }
            }
            _data.workingtime = workingtime;
            _data.account_id = _this.state.user.user.account_id;
            _this.props.dispatch(special_operate('update',{}, _data, function () {
                message.success('服务设置成功', 3);
                _this.props.updateUser(_data)
            }))
        })
    }
    render(){
        if(!this.state.user){
            return (<div>加载中</div>)
        }
        const {getFieldProps} = this.props.form;

        const dateData = [
            {label: '周一', value: 1},
            {label: '周二', value: 2},
            {label: '周三', value: 3},
            {label: '周四', value: 4},
            {label: '周五', value: 5},
            {label: '周六', value: 6},
            {label: '周日', value: 7}
        ];
        const serviceColumns = [
            {
                title: '时间段',
                dataIndex: 'label',
                width: 90,
                size: 'small'
            }, {
                title: '日期',
                dataIndex: 'active',
                render(text, record){
                    const _d = getFieldProps(record.id, {
                        rules: [
                            {type: 'array'}
                        ]
                    });

                    return (
                      <CheckboxGroup
                        {..._d}
                        options={dateData}
                      />
                    )
                }
            }
        ];

        return (
          <Form horizontal form={this.props.form}>
              <FormItem
                label="服务时段"
                {...formItemLayout.ignore}
              >
                  <Table columns={serviceColumns} dataSource={tempServiceData} pagination={false}/>
              </FormItem>
              <FormItem wrapperCol={formItemLayout.noLabel}>
                  <Button type="primary" onClick={this.handleSubmit.bind(this)}>保存</Button>
                  &nbsp;&nbsp;&nbsp;&nbsp;
                  <Button
                    onClick={this.setFieldsValue.bind(this)}
                  >
                      重置
                  </Button>
              </FormItem>
          </Form>
        )
    }
}
ServerInfo = Form.create()(ServerInfo);
class ResetPW extends  React.Component{
    constructor(props){
        super(props);
        this.state = {
            passBarShow: false, // 是否显示密码强度提示条
            rePassBarShow: false,
            passStrength: 'L', // 密码强度
            rePassStrength: 'L',
            user:this.props.user
        };
        this.checkPass = this.checkPass.bind(this);
        this.checkPass2 = this.checkPass2.bind(this);
        this.resetFields = this.resetFields.bind(this)

    }
    getPassStrength(value, type) {
        if (value) {
            let strength;
            // 密码强度的校验规则自定义，这里只是做个简单的示例
            if (value.length < 6) {
                strength = 'L';
            } else if (value.length <= 9) {
                strength = 'M';
            } else {
                strength = 'H';
            }
            if (type === 'password') {
                this.setState({ passBarShow: true, passStrength: strength });
            } else {
                this.setState({ rePassBarShow: true, rePassStrength: strength });
            }
        } else {
            if (type === 'pass') {
                this.setState({ passBarShow: false });
            } else {
                this.setState({ rePassBarShow: false });
            }
        }
    }
    checkPassword(rule, value, callback) {
        this.props.checkForm('account', 'password', rule, value, callback)
    }
    checkPass(rule, value, callback) {
        const form = this.props.form;
        this.getPassStrength(value, 'password');
        if (form.getFieldValue('password')) {
            form.validateFields(['rePass'], { force: true });
        }
        callback();
    }

    checkPass2(rule, value, callback) {
        const form = this.props.form;
        this.getPassStrength(value, 'rePass');
        if (value && value !== form.getFieldValue('password')) {
            callback('两次输入密码不一致！');
        } else {
            callback();
        }
    }
    renderPassStrengthBar(type) {
        const strength = type === 'password' ? this.state.passStrength : this.state.rePassStrength;
        const classSet = classNames({
            'ant-pwd-strength': true,
            'ant-pwd-strength-low': strength === 'L',
            'ant-pwd-strength-medium': strength === 'M',
            'ant-pwd-strength-high': strength === 'H'
        });
        const level = {
            L: '低',
            M: '中',
            H: '高'
        };
        return (
          <div style={{
            position:'absolute',
            right:'0',
            top:'0'
          }}>
              <ul className={classSet}>
                  <li className="ant-pwd-strength-item ant-pwd-strength-item-1"> </li>
                  <li className="ant-pwd-strength-item ant-pwd-strength-item-2"> </li>
                  <li className="ant-pwd-strength-item ant-pwd-strength-item-3"> </li>
                    <span className="ant-form-text">
                        {level[strength]}
                    </span>
              </ul>
          </div>
        );
    }
    handleSubmit(e) {
        const _this = this;
        _validate(e,_this,function(values){
            const sendData = {
                old:values.oldPW,
                changeto:values.rePass
            };
            _this.props.dispatch(putPW(sendData,function(){
                message.success('修改密码成功，请牢记新密码',1);
                _this.resetFields()
            },function(res){
                message.error(res.head.msg,1);
                _this.resetFields()
            }))
        });
    }
    resetFields(){
        this.setState({
            passBarShow: false, // 是否显示密码强度提示条
            rePassBarShow: false
        },function(){
            this.props.form.resetFields()
        })
    }
    render(){
        const { getFieldProps } = this.props.form;
        const oldPassProps = getFieldProps('oldPW', {
            rules: [
                { required: true, whitespace: true,message: '请输入原始密码' }
            ]
        });
        const passProps = getFieldProps('password', {
            rules: [
                { required: true, min:6,max:20,whitespace: true,message: '必填项' },
                { validator: this.checkPass },
                { validator: this.checkPassword.bind(this) }
            ]
        });
        const rePassProps = getFieldProps('rePass', {
            rules: [{
                required: true,
                whitespace: true,
                message: '请再次输入密码'
            }, {
                validator: this.checkPass2
            }]
        });
        return (
          <div>
              <Form horizontal form={this.props.form}>

                  <FormItem
                    {...formItemLayout}
                    label="原始密码"
                  >
                      <Input {...oldPassProps}
                        type="password"
                        onContextMenu={noop} onPaste={noop} onCopy={noop} onCut={noop}
                        autoComplete="off"
                        id="oldPW"
                      />
                  </FormItem>
                  <FormItem wrapperCol={formItemLayout.noLabel}>
                      设置新的密码
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label="新密码"
                  >
                      <Input
                        {...passProps}
                        type="password"
                        onContextMenu={noop}
                        onPaste={noop}
                        onCopy={noop}
                        onCut={noop}
                        autoComplete="off"
                        id="password"
                        style={{
                            position:'relative',
                            paddingRight:'100px'
                        }}
                      />
                      {this.state.passBarShow ? this.renderPassStrengthBar('password') : null}
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label="确认新密码"
                  >
                      <Input
                        {...rePassProps}
                        type="password"
                        onContextMenu={noop}
                        onPaste={noop}
                        onCopy={noop}
                        onCut={noop}
                        autoComplete="off"
                        id="rePass"
                      />
                  </FormItem>
                  <FormItem wrapperCol={formItemLayout.noLabel}>
                      <Button type="primary" onClick={this.handleSubmit.bind(this)}>修改密码</Button>
                      &nbsp;&nbsp;&nbsp;&nbsp;
                      <Button onClick={this.resetFields.bind(this)}>重置</Button>
                  </FormItem>
              </Form>

          </div>
        )
    }
}
ResetPW = Form.create()(ResetPW);
class specUser extends React.Component{
    constructor(props){
        super(props);
        this.state={
            user:this.props.user
        }
    }
    componentWillMount(){
        const _this = this;
        _this.props.dispatch(fetchDatum([
            {
                name: 'department',
                enabled: true
            }, {
                name: 'title',
                enabled: true
            }, {
                name: 'gender',
                enabled: true
            }, {
                name: 'modality',
                enabled: true
            }
        ], function (datas) {
            _this.props.dispatch(check_rules(function (rules) {
                _this.setState({
                    rules: rules.content,
                    data: datas
                })
            }));
        }));
        const attachment_type = {id:_this.state.user.user.specialist_id,type:'portrait'};
        _this.props.dispatch(fetchAttachByEntry(attachment_type,function (portrait) {
            let last = {};
            if(portrait.content.length> 1){
                _.forEach(portrait.content,(o,i)=>{
                    if((i+1)<portrait.content.length){
                        _this.props.dispatch(fetchAttachById(o.id,0));
                    }else{
                        last = o
                    }
                })
            }else{
                last = portrait.content[0]
            }
            _this.setState({
                portrait: {
                    id:last.id,
                    url:`${API_URL}attachment/${last.id}?accessToken=${_this.state.user.accessToken}`
                }
            })
        }));
    }
    componentDidMount(){}
    updateUserData(newData){
        if(window.sessionStorage){
            const sessionUser = JSON.parse(window.sessionStorage.getItem('user'));
            if(sessionUser){
                delete newData.attachment;
                let newUser = Object.assign({},sessionUser.user,newData);
                newUser = Object.assign({},sessionUser,{user:newUser});
                const str = JSON.stringify(newUser);
                window.sessionStorage.setItem('user',str);
                this.props.dispatch(getUser({content:newUser}));
            }
        }
    }
    checkForm(a, b, rule, value, callback) {
        const _r = eval(this.state.rules[a][b]['expr']),
          msg = this.state.rules[a][b]['rule'];
        (function () {
            const result = _r.test(value);
            if (!result && value) {
                callback(msg)
            } else {
                callback();
            }
        })()
    }
    componentWillReceiveProps(nextProp){
        this.setState({
            user:nextProp.user
        })
    }
    render(){
        return (
          <Tabs
            size="default"
          >
              <TabPane tab="基础信息" key="1">
                  <BaseInfo
                    user={this.state.user}
                    data={this.state.data}
                    checkForm={this.checkForm.bind(this)}
                    dispatch={this.props.dispatch}
                    portrait={this.state.portrait}
                    updateUser={this.updateUserData.bind(this)}
                  />
              </TabPane>
              <TabPane tab="专业信息" key="2">
                  <ProInfo
                    user={this.state.user}
                    data={this.state.data}
                    checkForm={this.checkForm.bind(this)}
                    dispatch={this.props.dispatch}
                    updateUser={this.updateUserData.bind(this)}
                  />
              </TabPane>
              <TabPane tab="修改密码" key="3">
                  <ResetPW
                    user={this.state.user}
                    checkForm={this.checkForm.bind(this)}
                    dispatch={this.props.dispatch}
                  />
              </TabPane>
              <TabPane tab="服务时段设置" key="4">
                  <ServerInfo
                    user={this.state.user}
                    data={this.state.data}
                    checkForm={this.checkForm.bind(this)}
                    dispatch={this.props.dispatch}
                    updateUser={this.updateUserData.bind(this)}
                  />
              </TabPane>
          </Tabs>
        )
    }
}
export default specUser = connect((state)=>{
    const {user} = state.rootReducer;
    return {user}
})(specUser)
